#include "sonic.h"
#include <intrins.h>

void delay_12us() {
	uchar data i;
	
	_nop_();
	_nop_();
	i =33;
	
	while(--i);
}

void sonic_init() {
	uchar i;
	
	for(i=0; i<8; i++) {
		TX = 1;
		delay_12us();
		TX = 0;
		delay_12us();
	}
}

uchar sonic_read() {
	uint time;
	
	CMOD = 0x00;
	CH = CL = 0;
	sonic_init();
	CR = 1;
	while(RX && !CF);
	CR = 0;
	if(!CF) {
		time = (CH << 8) | CL;
		return time*0.017;
	} else {
		CF = 0;
		return 255;
	}
}

